package com.swing.sky.system.framework.security.service;

import com.swing.sky.system.framework.security.exception.UserNotFountException;
import com.swing.sky.system.framework.security.exception.UserUnUsedException;
import com.swing.sky.system.module.domain.SysUserDO;
import com.swing.sky.system.module.service.SysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);
    @Resource
    private SysUserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUserDO user = userService.getUserByUsername(username);
        if (user == null) {
            log.info("\u60A8\u8F93\u5165\u7684\u7528\u6237:{} \u4E0D\u5B58\u5728!", username);
            throw new UserNotFountException(username + "\uFF1A\u7528\u6237\u540D\u6216\u5BC6\u7801\u9519\u8BEF\uFF0C\u8BF7\u91CD\u65B0\u8F93\u5165");
        }
        if (!user.getUse()) {
            log.info("\u60A8\u8F93\u5165\u7684\u7528\u6237:{} \u5DF2\u505C\u7528!", username);
            throw new UserUnUsedException(username + "\uFF1A\u8BE5\u7528\u6237\u5DF2\u88AB\u7BA1\u7406\u5458\u7981\u7528\uFF01");
        }
        return new UserDetailsImpl(user);
    }
}